#! /bin/bash -x
# 如果 baselib/protolib/cfgmmaptool 有变更就全编, 其余目录如果有头文件变更就进入相应目录进行编译

RED="\033[1;31m"
GREEN="\033[1;32m"
NONE="\033[0m"

PWD=$(pwd)
# 设置PWD为只读
readonly PWD

LOGFILE=${PWD}/build_log.txt
>${LOGFILE}

IF_ALL_MAKE=0;

function NewFile()
{
    if [[ $# -lt 2 ]]; then
        echo "参数数量错误"
        exit 1;
    fi

    local DIR="${PWD}/$1"
    local REFER_DIR="${PWD}/../debug/$1/"

    if [[ ! -d "$DIR" ]]; then
        echo -e "${RED}没有这个目录${DIR}${NONE}"
	    exit 1
    fi
    if [[ ! -d "$REFER_DIR" ]]; then
        echo -e "${RED}没有这个目录${REFER_DIR}${NONE}"
	    exit 1
    fi

    for SUFFIX in "${@:2}"; do
	    local OUTPUT=$(find $DIR \( -name "*.${SUFFIX}" \) -newer $REFER_DIR -print -quit)
        if [[ -n "$OUTPUT" ]]; then
            return 0 
        fi
    done

    return 1
}


function AllCompile()
{
    cd ${PWD} 2>/dev/null
        
    make clean
    local STATUS=$?

    if [[ $STATUS -ne 0 ]]; then
        echo "make clean 失败, 返回$STATUS"
        return $STATUS
    fi

    make debug=1
    STATUS=$?

    if [[ $STATUS -ne 0 ]]; then
        echo "make debug=1 失败, 返回$STATUS"
        return $STATUS
    fi
}

function Compile()
{
    cd ${PWD}/$1 2>/dev/null
        
    if [[ $2 -eq 1 ]]; then
        make clean
    fi  
        
    make mkdir
    make -j6 -fmakefile debug=1 2>>${LOGFILE}
}

# 检测目录变更
for OBJ in baselib protolib cfgmmaptool; do
    if NewFile $OBJ h cc cpp ; then
        IF_ALL_MAKE=1
        break
    fi
done;

if [[ $IF_ALL_MAKE -eq 1 ]]; then
    AllCompile
    exit $?
fi

for OBJ in commsvrd gamesvrd dbsvrd trfsvrd logsvrd gmsvrd namesvrd globalsvrd proxysvrd verifysvrd; do
    IF_CLEAN=0

    if NewFile $OBJ h; then
        IF_CLEAN=1
    fi

    Compile $OBJ $IF_CLEAN
done;
